package org.meb.speedway.process.sf;

import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.meb.speedway.process.model.LeagueEventData;
import org.meb.speedway.process.model.TeamData;

public class SFLeagueEventParserV1 implements SFEventParser {

	public LeagueEventData parse(String content) {
		Document doc = Jsoup.parse(content);
		TeamData homeTeam = extractTeam(doc.select("span#bts_1").get(0));
		if (homeTeam == null) {
			return null;
		}
		TeamData awayTeam = extractTeam(doc.select("span#bts_2").get(0));
		if (awayTeam == null) {
			return null;
		}
		LeagueEventData event = new LeagueEventData();
		event.setHomeTeam(homeTeam);
		event.setAwayTeam(awayTeam);
		return event;
	}

	private TeamData extractTeam(Element span) {
		try {
			TeamData team = new TeamData();
			Element teamAElem = span.previousElementSibling();
			team.setName(teamAElem.textNodes().get(0).text());
			Element table = span.parent().nextElementSibling();
			Elements rows = table.select("tbody > tr");
			team.setRiders(new ArrayList<String>());
			for (int i = 0; i < rows.size(); i++) {
				Element riderAElem = rows.get(i).select("td:eq(1) > a").get(0);
				team.getRiders().add(riderAElem.textNodes().get(0).text());
			}
			return team;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
